package org.argeproje.resim.ui.viewers;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

public class ImageCanvas extends Canvas{
	private static final long serialVersionUID = -3227840439829326918L;
    
	protected Image cvImage;
	protected Image cvOfflineImage;
	
	public ImageCanvas()
	{
	   cvImage = null;
	}
	
	public void loadImage(String filename)
	{
		cvImage = Toolkit.getDefaultToolkit().getImage(filename);
		cvOfflineImage = createImage(cvImage.getWidth(this),cvImage.getHeight(this));
		repaint();
	}
	
	public void loadImage(Image image)
	{
		cvImage = image;
		cvOfflineImage = createImage(cvImage.getWidth(this),cvImage.getHeight(this));
		repaint();
	}
	
	public void update(Graphics g)
	{
		Graphics offgc;
		Image offscreen = null;
		// create the offscreen buffer and associated Graphics
		offscreen = createImage(getSize().width, getSize().height);
		offgc = offscreen.getGraphics();
		// clear the exposed area
		offgc.setColor(getBackground());
		offgc.fillRect(0, 0, getSize().width, getSize().height);
		offgc.setColor(getForeground());
		// do normal redraw
		paint(offgc);
		// transfer offscreen to window
		g.drawImage(offscreen, 0, 0, this);
	}
	
	public void paint(Graphics g)
	{		
		if(cvImage!=null) g.drawImage(cvImage, 0, 0, this);	
	}
	
	protected void finalize() throws Throwable {
		cvImage = null;
		super.finalize();
	}
}
